package space.panker916.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import space.panker916.event.EventProducer;
import space.panker916.pojo.*;
import space.panker916.service.CommentService;
import space.panker916.service.DiscussPostService;
import space.panker916.service.LikeService;
import space.panker916.service.UserService;
import space.panker916.utils.HostHolder;
import space.panker916.utils.RedisKeyUtil;

import java.util.*;

import static space.panker916.utils.Constants.*;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController {
    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/add")
    @ResponseBody
    public R addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();

        if (user == null) return new R(403, "你还没有登录哦！");
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());

        discussPostService.addDiscussPost(post);

        // 触发发帖事件
        Event event = new Event();
        event.setUserId(user.getId());
        event.setTopic(TOPIC_PUBLISH);
        event.setEntityType(ENTITY_TYPE_POST);
        event.setEntityId(post.getId());
        eventProducer.fireEvent(event);

        // 计算帖子分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, post.getId());

        // 报错的情况，以后统一处理
        return new R(0, "发布成功");
    }

    @GetMapping("/detail/{discussPostId}")
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page page) {
        User user = hostHolder.getUser();

        // 帖子
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        model.addAttribute("post", post);

        // 作者
        User writer = userService.findUserById(post.getUserId());
        model.addAttribute("user", writer);

        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
        model.addAttribute("likeCount", likeCount);

        // 点赞状态
        int likeStatus = user == null ? 0 : likeService.findEntityLikeStatus(user.getId(), ENTITY_TYPE_POST, post.getId());
        model.addAttribute("likeStatus", likeStatus);

        // 评论分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setRows(post.getCommentCount());
        model.addAttribute("page", page);

        // 查出来的评论的列表（是 帖子 回复 ）
        List<Comment> commentList = commentService.findCommentsByEntity(ENTITY_TYPE_POST, post.getId(), page.getOffset(), page.getLimit());

        // 展示在前端的评论的VO（view object）类型
        List<Map<String, Object>> commentVoList = new ArrayList<>();

        for (Comment comment : commentList) {
            Map<String, Object> commentVo = new HashMap<>();

            commentVo.put("comment", comment);
            commentVo.put("user", userService.findUserById(comment.getUserId()));

            // 点赞数量
            likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
            commentVo.put("likeCount", likeCount);

            // 点赞状态
            likeStatus = user == null ? 0 : likeService.findEntityLikeStatus(user.getId(), ENTITY_TYPE_COMMENT, post.getId());
            commentVo.put("likeStatus", likeStatus);

            // 查出来的评论的列表（是 评论 回复）
            List<Comment> replyList = commentService.findCommentsByEntity(ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
            List<Map<String, Object>> replyVoList = new ArrayList<>();
            // 将该帖子的评论的回复也放进去（要区分 作者user 和 回复目标target）
            for (Comment reply : replyList) {
                Map<String, Object> replyVo = new HashMap<>();
                replyVo.put("reply", reply);    // 回复内容
                replyVo.put("user", userService.findUserById(reply.getUserId()));   // 作者
                User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());  // 回复目标
                replyVo.put("target", target);

                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                replyVo.put("likeCount", likeCount);

                // 点赞状态
                likeStatus = user == null ? 0 : likeService.findEntityLikeStatus(user.getId(), ENTITY_TYPE_COMMENT, post.getId());
                replyVo.put("likeStatus", likeStatus);

                replyVoList.add(replyVo);
            }

            commentVo.put("replies", replyVoList);      // 放入回复
            commentVo.put("replyCount", commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId()));  // 放入回复数量
            commentVoList.add(commentVo);
        }

        model.addAttribute("comments", commentVoList);

        return "/site/discuss-detail";
    }

    // 置顶操作（就是直接置顶（不算分数的））
    @PostMapping("/top")
    @ResponseBody
    public R setTop(int id) {
        discussPostService.updateTypeById(id, 1);

        // 再触发一次发帖事件（更新 elasticsearch 中的数据）
        Event event = new Event();
        event.setUserId(hostHolder.getUser().getId());
        event.setTopic(TOPIC_PUBLISH);
        event.setEntityType(ENTITY_TYPE_POST);
        event.setEntityId(id);
        eventProducer.fireEvent(event);

        return new R(0);
    }

    // 加精操作（加精算分数）
    @PostMapping("/wonderful")
    @ResponseBody
    public R setWonderful(int id) {
        discussPostService.updateStatusById(id, 1);

        // 再触发一次发帖事件（更新 elasticsearch 中的数据）
        Event event = new Event();
        event.setUserId(hostHolder.getUser().getId());
        event.setTopic(TOPIC_PUBLISH);
        event.setEntityType(ENTITY_TYPE_POST);
        event.setEntityId(id);
        eventProducer.fireEvent(event);

        // 计算帖子分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, id);

        return new R(0);
    }


    // 删除操作（状态设置为 2 ，拉黑操作）
    @PostMapping("/delete")
    @ResponseBody
    public R setDelete(int id) {
        discussPostService.updateStatusById(id, 2);

        // 再触发删帖事件（将帖子从 es 中删除）
        Event event = new Event();
        event.setUserId(hostHolder.getUser().getId());
        event.setTopic(TOPIC_DELETE);
        event.setEntityType(ENTITY_TYPE_POST);
        event.setEntityId(id);
        eventProducer.fireEvent(event);

        return new R(0);
    }
}
